/*
 * @Author: linZeJian
 * @Date: 2022-01-27 16:09:58
 * @LastEditors: linZeJian
 * @LastEditTime: 2022-05-12 15:52:57
 * @Description:
 */
import axios from "axios";
import {
  Notify,
  Toast
} from "vant";

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 100000,
});

// vant加载页
let requestNum = 0;
const addLoading = () => {
  // 增加loading 如果pending请求数量等于1，弹出loading, 防止重复弹出
  requestNum++;
  if (requestNum == 1) {
    Toast.loading({
      message: "加载中 \n 请稍等...",
      duration: 0,
      forbidClick: true,
    });
  }
};
const cancelLoading = () => {
  // 取消loading 如果pending请求数量等于0，关闭loading
  requestNum--;
  if (requestNum === 0) Toast.clear();
};

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    console.log('config', config)
    // 加载动画
    if (config.loading) {
      addLoading();
    }
    console.log('process.env.VUE_APP_ENV :>> ', process.env.VUE_APP_ENV);
    // 统一设置用户身份 token
    // 是否需要设置 token
    let token = process.env.VUE_APP_TOKEN;
    if (process.env.VUE_APP_ENV == "development") {
      config.headers["X-Oars-Token"] = `${token}`;
      config.headers.Authorization = `Bearer ${token}`;
    }
    // filebase接口认证
    // console.log('config', config)
    if (
      process.env.VUE_APP_ENV == "development" &&
      config.baseURL == "/filebase"
    ) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 相应拦截器
request.interceptors.response.use(
  function (response) {
    const {
      loading = true
    } = response.config;
    if (loading) cancelLoading();
    // 统一设置接口相应错误, 比如 token 过期失效, 服务端异常
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    // 获取错误信息
    const errorCode = {
      "401": "认证失败，无法访问系统资源",
      "403": "当前操作没有权限",
      "404": "访问资源不存在",
      default: "系统未知错误，请反馈给管理员",
    };
    const msg = response.data.msg || errorCode[code] || errorCode["default"];
    if (code !== 200 && code != 10000) {
      Notify(msg);
      return Promise.reject("error");
    } else {
      return response.data;
    }
  },
  function (error) {
    // Do something with response error
    const {
      loading = true
    } = error.config;
    if (loading) cancelLoading();
    console.log("axios response 拦截器:" + error);
    let {
      message
    } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Notify({
      message: message,
      type: "danger",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default request;
